package com.resou.reader.reading;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.glong.reader.TurnStatus;
import com.glong.reader.config.ColorsConfig;
import com.glong.reader.widget.EffectOfCover;
import com.glong.reader.widget.EffectOfNon;
import com.glong.reader.widget.EffectOfRealBothWay;
import com.glong.reader.widget.EffectOfSlide;
import com.glong.reader.widget.PageChangedCallback;
import com.glong.reader.widget.ReaderResolve;
import com.glong.reader.widget.ReaderView;
import com.resou.reader.R;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.ChapterItemBean;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookdetail.BookDetailActivity;
import com.resou.reader.bookdetail.adapter.CatalogueAdapter;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.commom.Constant;
import com.resou.reader.data.reading.Reading;
import com.resou.reader.reader.m.SimpleAnimatorListener;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.reader.utils.SpUtils;
import com.resou.reader.reader.view.CollectionHintFragment;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.view.ChoiceView;
import com.resou.reader.view.Loading;

import java.util.List;

import butterknife.BindView;

public class ReadingActivity extends ResouBaseActivity<ReadingPresenter> implements ReadingContract.View {
    private static final String TAG = "ReadingActivity-App";

    private static final int ANIM_DURATION = 150;
    public static final String BOOK_ID = "book_id";
    public static final String CHAPTER_ID = "chapter_id";
    public static final String TO_NEW_CHAPTER = "to_new_chapter";
    public static final String BOOK_NAME = "book_name";
    public static final String BOOK_DETAIL = "book_detail";
    public static String START_FROM_POSITION = "start_from_position";
    public static final String START_FROM_BOOKSHELF = "start_from_bookshelf";
    public static final String START_FROM_BOOK_DETAIL = "start_from_book_detail";
    public static final String START_FROM_READ_HISTORY = "start_from_read_history";
    public static int[] BG_COLOR = {0xFFF7F3EF, 0xFFd8c9aa, 0xFFcce8cf, 0xFFb69b94};//白，黄，绿，红
    public static int[] BG_SPACE = {70, 50, 30};
    public static int MIN_TEXT_SIZE;
    public static int MAX_TEXT_SIZE;
    public static int DEFAULT_TEXT_SIZE;

    private static final int MSG_ENTER = 0;//进入动画
    private static final int MSG_EXIT = 1;//退出动画

    private static final int STATE_HIDE = 0;//隐藏
    private static final int STATE_SHOW = 1;//展示
    private static final int STATE_HIDING = 2;//正在隐藏
    private static final int STATE_SHOWING = 3;//正在展示
    @BindView(R.id.reader_view)
    ReaderView mReaderView;
    @BindView(R.id.btn_real_anim)
    TextView btnRealAnim;
    @BindView(R.id.btn_cover_anim)
    TextView btnCoverAnim;
    @BindView(R.id.btn_slide_anim)
    TextView btnSlideAnim;
    @BindView(R.id.btn_no_anim)
    TextView btnNoAnim;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.frame_layout)
    FrameLayout frameLayout;

    private int layoutState = STATE_HIDE;//上下layout的隐藏状态

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @BindView(R.id.navigation)
    NavigationView mNavigationView;
    @BindView(R.id.reader_catalogue_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.title_layout)
    FrameLayout mTitleLayout;
    @BindView(R.id.bottom_layout)
    ConstraintLayout mBottomLayout;
    @BindView(R.id.coordinator)
    CoordinatorLayout mCoordinatorLayout;
    @BindView(R.id.seekBar)
    SeekBar mSeekBar;

    @BindView(R.id.setting_parent)
    ConstraintLayout mSettingParent;
    @BindView(R.id.back_image)
    ImageView mBackImage;
    @BindView(R.id.center_text)
    TextView mCenterText;
    @BindView(R.id.right_share)
    ImageView mShareImage;
    @BindView(R.id.right_add_shelf)
    ImageView mAddShelfImage;
    @BindView(R.id.pre_chapter_text)
    TextView mPreChapterText;
    @BindView(R.id.next_chapter_text)
    TextView mNextChapterText;
    @BindView(R.id.catalogue_text)
    TextView mCatalogueText;
    @BindView(R.id.day_night_text)
    TextView mDayNightText;
    @BindView(R.id.setting_text)
    TextView mSettingText;
    @BindView(R.id.comment_text)
    TextView mCommentText;
    @BindView(R.id.light_seek)
    SeekBar mLightSeekBar;
    @BindView(R.id.order_btn)
    TextView mOrderText;

    Loading loading = new Loading();
    private ReaderView.ReaderManager mReaderManager;

    private CatalogueAdapter mCatalogueAdapter;
    private ReadingAdapter mReadingAdapter;
    private boolean mIsToNewChapter;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ENTER:
                    enterAnim();
                    break;
                case MSG_EXIT:
                    exitAnim();
                    break;
            }
        }
    };
    private ReaderResolve mReaderResolve;
    private List<ChapterItemBean> mChapterList;
    private BookDetailBean mBookDetailBean;
    private ReaderHistory mReaderHistory;

    /**
     * 从书本详情页的最新章节进入
     *
     * @param context
     * @param bookId
     * @param toNewChapter
     */
    public static void start(Context context, String bookId, boolean toNewChapter) {
        Intent starter = new Intent(context, ReadingActivity.class);
        starter.putExtra(BOOK_ID, bookId);
        START_FROM_POSITION = START_FROM_BOOK_DETAIL;
        starter.putExtra(TO_NEW_CHAPTER, toNewChapter);
        context.startActivity(starter);
    }

    /**
     * 从书架进入
     *
     * @param context
     * @param bookId
     */
    public static void start(Context context, String bookId) {
        Intent starter = new Intent(context, ReadingActivity.class);
        starter.putExtra(BOOK_ID, bookId);
//        starter.putExtra(BOOK_NAME, bookName);
        START_FROM_POSITION = START_FROM_BOOKSHELF;
//        starter.putExtra(CHAPTER_ID, chapterId);
        context.startActivity(starter);
    }

    /**
     * 从书本详情页的"开始阅读"按钮进入
     *
     * @param context
     */
    public static void start(Context context) {
        Intent starter = new Intent(context, ReadingActivity.class);
//        starter.putExtra(BOOK_DETAIL, bookDetailBean);
        START_FROM_POSITION = START_FROM_BOOK_DETAIL;
//        starter.putExtra(START_FROM_READ_HISTORY, bookDetailBean);
        context.startActivity(starter);
    }

    @Override
    protected void initStatusBar() {
        //已在主题中设置全屏，这里无需设置
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ReadingPresenter(this);
    }

    @Override
    protected void initView() {
//        Loading.getInstance().show(getSupportFragmentManager());
//        getSupportFragmentManager().beginTransaction().add(R.id.coordinator, loading).hide(loading).commitAllowingStateLoss();
        //加载基本文字配置
        MIN_TEXT_SIZE = (int) getResources().getDimension(R.dimen.qb_px_35);
        MAX_TEXT_SIZE = (int) getResources().getDimension(R.dimen.qb_px_120);
        DEFAULT_TEXT_SIZE = (int) getResources().getDimension(R.dimen.qb_px_65);
        mReading = new Reading();
        mReading.setBookId(getIntent().getStringExtra(BOOK_ID));
        TextView catalogueText = (TextView) findViewById(R.id.catalogue_text);
//        catalogueText.setOnClickListener(this::onClick);
//        mChapterId = getIntent().getStringExtra(CHAPTER_ID);
        initDefaultMenu();
        initSeekBar();
        initReader();
        initRecyclerView();
        initDrawerLayout();
        initSetting();
        setTheme(SpUtils.getTheme(this));
    }

    private void initDefaultMenu() {
        mTitleLayout.setTranslationY(-mTitleLayout.getLayoutParams().height);
        mBottomLayout.setTranslationY(mBottomLayout.getLayoutParams().height);
        mSettingParent.setTranslationY(mSettingParent.getLayoutParams().height);

        int index = SpUtils.getAnimIndex(this);
        switch (index) {
            case 0:
                mReaderView.setEffect(new EffectOfRealBothWay(this));
                selectView(btnRealAnim);
                break;
            case 1:
                selectView(btnCoverAnim);
                mReaderView.setEffect(new EffectOfCover(this));
                break;
            case 2:
                selectView(btnSlideAnim);
                mReaderView.setEffect(new EffectOfSlide(this));
                break;
            case 3:
                selectView(btnNoAnim);
                mReaderView.setEffect(new EffectOfNon(this));
                break;
        }
    }

    private void initSeekBar() {
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                DLog.d(TAG, "mSeekBar onProgressChanged progress: " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                DLog.d(TAG, "mSeekBar onStopTrackingTouch progress: " + seekBar.getProgress());
                mReaderManager.toSpecifiedChapter(seekBar.getProgress(), 0);
            }
        });

        mLightSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                DLog.d(TAG, "mLightSeekBar onProgressChanged progress: " + progress);
//                ScreenUtils.changeAppBrightness(ReadingActivity.this, progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                DLog.d(TAG, "mLightSeekBar onStopTrackingTouch progress: " + seekBar.getProgress());
            }
        });
        mLightSeekBar.setProgress(ScreenUtils.getSystemBrightness(this));
    }

    private void initDrawerLayout() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int i) {
            }
        });
    }

    private void initReader() {
        mReaderManager = new ReaderView.ReaderManager();
        mReaderView.setReaderManager(mReaderManager);
        mReadingAdapter = new ReadingAdapter(mReaderView);
        mReaderView.setAdapter(mReadingAdapter);
        mReaderResolve = mReaderManager.getReaderResolve();
        mReaderView.setPageChangedCallback(new PageChangedCallback() {
            @Override
            public TurnStatus toPrevPage() {
                TurnStatus turnStatus = mReaderManager.toPrevPage();
                if (turnStatus == TurnStatus.NO_PREV_CHAPTER) {
                    ToastUtil.makeShortToast("没有上一页啦");
                }
                chapterItemBean = mChapterList.get(mReaderResolve.getChapterIndex());
//                mPresenter.saveReadHistory(mReading, mReaderResolve.getChapterIndex(), chapterItemBean.getChapterId(),
//                        chapterItemBean.getChapterName(), mReaderResolve.getPageIndex(), mReaderResolve.getCharIndex(), mReading.getCoverUrl());
                return turnStatus;
            }

            @Override
            public TurnStatus toNextPage() {
                TurnStatus turnStatus = mReaderManager.toNextPage();
                if (turnStatus == TurnStatus.NO_NEXT_CHAPTER) {
                    ToastUtil.makeShortToast("没有下一页啦");

                }
                chapterItemBean = mChapterList.get(mReaderResolve.getChapterIndex());
//                mPresenter.saveReadHistory(mReading, mReaderResolve.getChapterIndex(), chapterItemBean.getChapterId(),
//                        chapterItemBean.getChapterName(), mReaderResolve.getPageIndex(), mReaderResolve.getCharIndex(), mReading.getCoverUrl());
//                Log.d(TAG, "toNextPage: " + mReading.getCoverUrl());
                return turnStatus;
            }
        });
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCatalogueAdapter = new CatalogueAdapter((adapter, itemView, index) -> {
            //dismiss drawLayout
            dismissCatalogue();
            mReaderManager.toSpecifiedChapter(index, 0);
        });
        mRecyclerView.setAdapter(mCatalogueAdapter);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_reading;
    }

    @Override
    public void retryRefreshData() {

    }

    private Reading mReading;

    @Override
    public void initData() {
        mBookDetailBean = mPresenter.loadBookDetailBean(mReading.getBookId());
        if (mBookDetailBean != null) {
            mReading.setBookName(mBookDetailBean.getNovelName());
            mReading.setCoverUrl(mBookDetailBean.getCoverUrl());
        } else {
//            BookCollection collection = mPresenter.loadBookCollection();
//            if (collection != null) {
//                mReading.setCoverUrl(collection.getPicUrl());
//                mReading.setBookId(collection.getBookId());
//                if (!TextUtils.isEmpty(collection.getName())) {
//                    mReading.setBookName(collection.getName());
//                }
//                if (!TextUtils.isEmpty(collection.getHistoryChapterId())) {
//                    mReading.setChapterId(collection.getHistoryChapterId());
//                }
//                if (!TextUtils.isEmpty(collection.getHistoryChapterName())) {
//                    mReading.setChapterId(collection.getHistoryChapterName());
//                }
//                mReading.setChapterIndex(collection.getChapterIndex());
//                mReading.setPageIndex(collection.getPageIndex());
//                mReading.setCharIndex(collection.getCharIndex());
//            }
        }
//        else {
//            //一般打开book详情页添加书籍，mBookDetailBean不会为空
//            //如果此书是同步来的书籍，则不会进入书籍详情页
//            //从书架找
//        }

        //从阅读历史获取上次阅读的记录
        mReaderHistory = mPresenter.getReadHistory(mReading.getBookId());

        if (mReaderHistory != null) {
            mReading.setBookId(mReaderHistory.getBookId());
            if (!TextUtils.isEmpty(mReaderHistory.getName())) {
                mReading.setBookName(mReaderHistory.getName());
            }
            if (!TextUtils.isEmpty(mReaderHistory.getHistoryChapterId())) {
                mReading.setChapterId(mReaderHistory.getHistoryChapterId());
            }
            if (!TextUtils.isEmpty(mReaderHistory.getHistoryChapterName())) {
                mReading.setChapterId(mReaderHistory.getHistoryChapterName());
            }
            mReading.setChapterIndex(mReaderHistory.getChapterIndex());
            mReading.setPageIndex(mReaderHistory.getPageIndex());
            mReading.setCharIndex(mReaderHistory.getCharIndex());

            mSeekBar.setProgress(mReaderHistory.getChapterIndex());
        } else {
            mSeekBar.setProgress(0);
        }
        mIsToNewChapter = getIntent().getBooleanExtra(TO_NEW_CHAPTER, false);
        mPresenter.loadChapterList(mReading.getBookId());
    }

    /**
     * 最后阅读的章节
     */
    ChapterItemBean chapterItemBean;

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 在用户从未进入过书籍详情页的时候，mBookDetailBean始终为null
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void setChapterList(List<ChapterItemBean> chapters) {
        mChapterList = chapters;
        mCatalogueAdapter.setList(mChapterList);
        mReadingAdapter.setChapterList(mChapterList);
        mReadingAdapter.notifyDataSetChanged();
        mSeekBar.setMax(mChapterList.size() - 1);
        showContent();

        mReaderManager.toSpecifiedChapter(mReading.getChapterIndex(), mReading.getCharIndex());
        if (mIsToNewChapter) {
            mReaderManager.toSpecifiedChapter(mChapterList.size() - 1, 0);
            mSeekBar.setProgress(mChapterList.size() - 1);
        }
        ChapterItemBean bean = mChapterList.get(0);
        mCenterText.setText(bean.getBookName());
    }

    @Override
    public void finish() {
        if (!mPresenter.isAlreadyAddShelf(mReading.getBookId())) {
            new CollectionHintFragment(new CollectionHintFragment.Callback() {
                @Override
                public void onOkButtonClicked() {
                    if (mBookDetailBean != null) {
                        mPresenter.addToBookShelf(mBookDetailBean);
                    }
                    ReadingActivity.super.finish();
                }

                @Override
                public void onCancelButtonClicked() {
                    ReadingActivity.super.finish();
                }
            }).show(getSupportFragmentManager(), "CollectionHintFragment");
        } else {
            super.finish();
            overridePendingTransition(R.anim.anim_no, R.anim.anim_detail_exit);
        }
    }

    private void initSetting() {
        //设置默认text大小
        mReaderView.setTextSize(SpUtils.getTextSize(this, DEFAULT_TEXT_SIZE));
      /*  switch (SpUtils.getSpaceIndex(this)) {
            case 0:
                mLastSpaceView = findViewById(R.id.space_3_btn);
                //设置文本文字间距
                mReaderView.setLineSpace(BG_SPACE[0]);
                break;
            case 1:
                mLastSpaceView = findViewById(R.id.space_4_btn);
                //设置文本文字间距
                mReaderView.setLineSpace(BG_SPACE[1]);
                break;
            case 2:
                mLastSpaceView = findViewById(R.id.space_5_btn);
                //设置文本文字间距
                mReaderView.setLineSpace(BG_SPACE[2]);
                break;
        }*/
        mLastSpaceView.setSelected(true);

      /*  switch (SpUtils.getBgIndex(this)) {
            case 0:
                mLastChoiceView = (ChoiceView) findViewById(R.id.reader_bg_0);
                mReaderView.setBackgroundColor(BG_COLOR[0]);
                break;
            case 1:
                mLastChoiceView = (ChoiceView) findViewById(R.id.reader_bg_1);
                mReaderView.setBackgroundColor(BG_COLOR[1]);
                break;
            case 2:
                mLastChoiceView = (ChoiceView) findViewById(R.id.reader_bg_2);
                mReaderView.setBackgroundColor(BG_COLOR[2]);
                break;
            case 3:
                mLastChoiceView = (ChoiceView) findViewById(R.id.reader_bg_3);
                mReaderView.setBackgroundColor(BG_COLOR[3]);
                break;
        }*/
//        {0xFFF7F3EF, 0xFFd8c9aa, 0xFFcce8cf, 0xFFb69b94}
        mLastChoiceView.setChoice(true);
    }

    private boolean isSettingShow() {
        //偏移量==0，默认显示
        return mSettingParent.getTranslationY() == 0;
    }

    private boolean isMenuShow() {
        //偏移量为0时，表示显示
        return mTitleLayout.getTranslationY() == 0 &&
                mBottomLayout.getTranslationY() == -mBottomLayout.getLayoutParams().height;
    }

    private long mDownTime;
    private float mDownX;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int screenWidth = ScreenUtils.getScreenWidth();
        int screenHeight = ScreenUtils.getScreenHeight();
        float x = ev.getX();
        float y = ev.getY();
        int longClickTime = ViewConfiguration.getLongPressTimeout();
        int touchSlop = ViewConfiguration.get(this).getScaledPagingTouchSlop();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isShow() || isSettingShow()) {
                    mDownTime = System.currentTimeMillis();
                } else if (ev.getX() > screenWidth / 3 && ev.getX() < screenWidth * 2 / 3) {
                    mDownTime = System.currentTimeMillis();
                } else {
                    mDownTime = 0;
                }
                mDownX = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                if (mSettingParent.getTranslationY() == 0 && y < (screenHeight - mSettingParent.getLayoutParams().height)) {
                    Log.d(TAG, "dispatchTouchEvent:  hideSettingLayout();");
                    hideSettingLayout();
                    return true;
                }
//
                if (isShow() && y > mTitleLayout.getHeight() && y < (screenHeight - mBottomLayout.getHeight())) {
                    dismiss();
                    return true;
                }
                if (System.currentTimeMillis() - mDownTime < longClickTime && (Math.abs(ev.getX() - mDownX) < touchSlop)) {
                    if (!isShow() && !isSettingShow() && !mDrawerLayout.isDrawerOpen(mNavigationView)) {
                        Log.d(TAG, "show menuView!");
                        show();
                        return true;
                    }
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void showLoading() {
        if (!loading.isShow()) {
            Log.d(TAG, "showLoading: ");
            getSupportFragmentManager().beginTransaction().show(loading).commitAllowingStateLoss();
        }
    }

    public void dismissLoading() {
        Log.d(TAG, "dismissLoading: ");
        getSupportFragmentManager().beginTransaction().hide(loading).commitAllowingStateLoss();
    }

    public boolean isShow() {
        return layoutState == STATE_SHOW;
    }

    public boolean dismissCatalogue() {
        if (mDrawerLayout.isDrawerOpen(mNavigationView)) {
            mDrawerLayout.closeDrawer(mNavigationView);
            return true;
        }
        return false;
    }

    private View mLastSpaceView;
    private ChoiceView mLastChoiceView;

  /*  @OnClick({R.id.back_image, R.id.right_share, R.id.pre_chapter_text, R.id.next_chapter_text, R.id.catalogue_text,
            R.id.day_night_text, R.id.setting_text, R.id.comment_text, R.id.light_seek,
            R.id.space_3_btn, R.id.space_4_btn, R.id.space_5_btn, R.id.reader_bg_0, R.id.reader_bg_2,
            R.id.reader_bg_3, R.id.reader_bg_1, R.id.text_size_dec_btn, R.id.text_size_add_btn, R.id.right_add_shelf,
            R.id.btn_real_anim, R.id.btn_cover_anim, R.id.btn_slide_anim, R.id.btn_no_anim, R.id.order_btn
            , R.id.feed_back_text})
// R.id.title_layout, R.id.bottom_layout,R.id.setting_parent,
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_image:
                finish();
                break;
            case R.id.right_share:

                break;
            case R.id.pre_chapter_text:
                TurnStatus turnStatus = mReaderManager.toPrevChapter();
                if (turnStatus == TurnStatus.LOAD_SUCCESS) {
                    mReaderView.invalidateBothPage();
                    mSeekBar.setProgress(mSeekBar.getProgress() - 1);
                } else if (turnStatus == TurnStatus.DOWNLOADING) {
                    mSeekBar.setProgress(mSeekBar.getProgress() - 1);
                } else if (turnStatus == TurnStatus.NO_PREV_CHAPTER) {
                    Toast.makeText(this, "没有上一章啦", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.next_chapter_text:
                TurnStatus turnStatus2 = mReaderManager.toNextChapter();
                if (turnStatus2 == TurnStatus.LOAD_SUCCESS) {
                    mReaderView.invalidateBothPage();
                    mSeekBar.setProgress(mSeekBar.getProgress() + 1);
                } else if (turnStatus2 == TurnStatus.DOWNLOADING) {
                    mSeekBar.setProgress(mSeekBar.getProgress() + 1);
                } else if (turnStatus2 == TurnStatus.NO_NEXT_CHAPTER) {
                    Toast.makeText(this, "没有下一章啦", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.catalogue_text:
                mDrawerLayout.openDrawer(mNavigationView);
                mReadingAdapter.notifyDataSetChanged();
                dismiss();
                break;
            case R.id.day_night_text:
                switchTheme();
                break;
            case R.id.setting_text:
                dismissNoAnimation();
                showSettingLayout();
                break;
            case R.id.comment_text:
                break;
            case R.id.right_add_shelf:
                //加入书架
                v.setVisibility(View.GONE);
                BookDetailActivity.sIsAddedBookCollection = true;
                Toast.makeText(this, getResources().getString(R.string.already_added_in_book_shelf), Toast.LENGTH_SHORT).show();
                break;
            case R.id.title_layout:
            case R.id.bottom_layout:
            case R.id.setting_parent:
                break;
            case R.id.space_3_btn:
                selectSpace(v, 0);
                break;
            case R.id.space_4_btn:
                selectSpace(v, 1);
                break;
            case R.id.space_5_btn:
                selectSpace(v, 2);
                break;
            case R.id.reader_bg_0:
                selectChoice((ChoiceView) v, 0);
                break;
            case R.id.reader_bg_1:
                selectChoice((ChoiceView) v, 1);
                break;
            case R.id.reader_bg_2:
                selectChoice((ChoiceView) v, 2);
                break;
            case R.id.reader_bg_3:
                selectChoice((ChoiceView) v, 3);
                break;
            case R.id.light_seek:
                break;
            case R.id.text_size_dec_btn:
                decTextSize(SpUtils.getTextSize(this, DEFAULT_TEXT_SIZE));
                break;
            case R.id.text_size_add_btn:
                addTextSize(SpUtils.getTextSize(this, DEFAULT_TEXT_SIZE));
                break;
            case R.id.btn_real_anim:
                setAnimation(0, v);
                break;
            case R.id.btn_cover_anim:
                setAnimation(1, v);
                break;
            case R.id.btn_slide_anim:
                setAnimation(2, v);
                break;
            case R.id.btn_no_anim:
                setAnimation(3, v);
                break;
            case R.id.order_btn:
                orderCatalogue();
                break;
            case R.id.feed_back_text:
                if (UserInstance.isLogin()) {
                    String nickname = UserInstance.getLoginData().getNickName();
                    if (!TextUtils.isEmpty(nickname)) {
                        FeedbackAPI.setUserNick(nickname);
                    }
                }
                FeedbackAPI.openFeedbackActivity();
                break;
        }
    }*/

    private void orderCatalogue() {
        mCatalogueAdapter.reverse();
        if (getString(R.string.order_back).equals(mOrderText.getText().toString())) {
            mOrderText.setText(getString(R.string.order_normal));
        } else {
            mOrderText.setText(getString(R.string.order_back));
        }
    }

    /**
     * 设置翻页动画
     *
     * @param index
     * @param v
     */
    private void setAnimation(int index, View v) {
        if (SpUtils.getAnimIndex(this) != index) {
            switch (index) {
                case 0:
                    mReaderView.setEffect(new EffectOfRealBothWay(this));
                    break;
                case 1:
                    mReaderView.setEffect(new EffectOfCover(this));
                    break;
                case 2:
                    mReaderView.setEffect(new EffectOfSlide(this));
                    break;
                case 3:
                default:
                    mReaderView.setEffect(new EffectOfNon(this));
                    break;
            }
            selectView(v);
            SpUtils.setAnimIndex(this, index);
        }
    }

    private void addTextSize(int textSize) {
        if (textSize < MAX_TEXT_SIZE) {
            textSize += 3;
            SpUtils.setTextSize(this, textSize);
            mReaderView.setTextSize(textSize);
        }
    }

    private void decTextSize(int textSize) {
        if (textSize > MIN_TEXT_SIZE) {
            textSize -= 3;
            SpUtils.setTextSize(this, textSize);
            mReaderView.setTextSize(textSize);
        }
    }

    private void selectSpace(View v, int index) {
        SpUtils.setSpaceIndex(this, index);
        if (mLastSpaceView != null)
            mLastSpaceView.setSelected(false);
        v.setSelected(true);
        mLastSpaceView = v;
        mReaderView.setLineSpace(BG_SPACE[index]);
    }

    private void selectChoice(ChoiceView v, int index) {
        SpUtils.setBgIndex(this, index);
        if (mLastChoiceView != null) {
            mLastChoiceView.setChoice(false);
        }
        switch (index) {
            case 0:
                mReaderView.setBackgroundColor(BG_COLOR[0]);
                break;
            case 1:
                mReaderView.setBackgroundColor(BG_COLOR[1]);
                break;
            case 2:
                mReaderView.setBackgroundColor(BG_COLOR[2]);
                break;
            case 3:
                mReaderView.setBackgroundColor(BG_COLOR[3]);
                break;
        }
        v.setChoice(true);
        mLastChoiceView = v;
    }

    private void showSettingLayout() {
        ObjectAnimator.ofFloat(mSettingParent, "translationY", 0).setDuration(ANIM_DURATION).start();
        frameLayout.setVisibility(View.VISIBLE);
    }

    private void hideSettingLayout() {
        ObjectAnimator.ofFloat(mSettingParent, "translationY", mSettingParent.getLayoutParams().height).setDuration(ANIM_DURATION).start();
        frameLayout.setVisibility(View.GONE);

    }

    public void show() {
        if (layoutState == STATE_HIDE) {
            mHandler.sendEmptyMessage(MSG_ENTER);
            frameLayout.setVisibility(View.VISIBLE);
        }
    }

    public void dismiss() {
        if (layoutState == STATE_SHOW) {
            mHandler.sendEmptyMessage(MSG_EXIT);
            frameLayout.setVisibility(View.GONE);
        }
    }

    private void dismissNoAnimation() {
        mTitleLayout.setTranslationY(-mTitleLayout.getLayoutParams().height);
        mBottomLayout.setTranslationY(mBottomLayout.getLayoutParams().height);
        layoutState = STATE_HIDE;
    }

    private void setTheme(boolean isNight) {
        if (isNight) {//设置成晚上
            mTitleLayout.setBackgroundColor(0xee0c0c0c);
            mBottomLayout.setBackgroundColor(0xee0c0c0c);
            mBackImage.setImageResource(R.mipmap.ic_read_back_night);
            mCenterText.setTextColor(Color.WHITE);
            mShareImage.setImageResource(R.mipmap.ic_read_share_night);
            mAddShelfImage.setImageResource(R.mipmap.ic_read_add_shelf_night);
            mPreChapterText.setTextColor(Color.WHITE);
            mNextChapterText.setTextColor(Color.WHITE);
            mCatalogueText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_categue_night), null, null);
            mDayNightText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_night), null, null);
            mSettingText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_setting_night), null, null);
            mCommentText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_comment_night), null, null);
            mCatalogueText.setTextColor(Color.WHITE);
            mDayNightText.setTextColor(Color.WHITE);
            mDayNightText.setText(R.string.mode_day);
            mSettingText.setTextColor(Color.WHITE);
            mCommentText.setTextColor(Color.WHITE);

//            mReaderView.setColorsConfig(getResources().getColor(R.color.night_text_color));
            mReaderView.setBackgroundColor(getResources().getColor(R.color.reader_bg_night));
            int textColor = getResources().getColor(R.color.night_text_color);
            mReaderView.setColorsConfig(new ColorsConfig(textColor, textColor));
            mSeekBar.setSelected(true);
        } else {
            mTitleLayout.setBackgroundColor(0xeeffffff);
            mBottomLayout.setBackgroundColor(0xeeffffff);
            mBackImage.setImageResource(R.mipmap.ic_read_back_day);
            mCenterText.setTextColor(Color.BLACK);
            mShareImage.setImageResource(R.mipmap.ic_read_share_day);
            mAddShelfImage.setImageResource(R.mipmap.ic_read_add_shelf_day);
            mPreChapterText.setTextColor(Color.BLACK);
            mNextChapterText.setTextColor(Color.BLACK);
            mCatalogueText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_categue_day), null, null);
            mDayNightText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_day), null, null);
            mSettingText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_setting_day), null, null);
            mCommentText.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.ic_read_comment_day), null, null);
            mCatalogueText.setTextColor(Color.BLACK);
            mDayNightText.setTextColor(Color.BLACK);
            mDayNightText.setText(R.string.mode_night);
            mSettingText.setTextColor(Color.BLACK);
            mCommentText.setTextColor(Color.BLACK);
            mReaderView.setColorsConfig(new ColorsConfig(Color.BLACK, Color.BLACK));
            mReaderView.setBackgroundColor(BG_COLOR[SpUtils.getBgIndex(this)]);
            mSeekBar.setSelected(false);
        }
        SpUtils.setTheme(this, isNight);
    }

    private void switchTheme() {
        boolean isNight = SpUtils.getTheme(this);
        setTheme(!isNight);
    }

    /**
     * @param view 选中View
     */
    private void selectView(View view) {
        ViewParent parent = view.getParent();
        if (parent != null) {
            ViewGroup parentGroup = (ViewGroup) parent;
            for (int i = 0, childCount = parentGroup.getChildCount(); i < childCount; i++) {
                View child = parentGroup.getChildAt(i);
                child.setSelected(false);
            }
        }
        view.setSelected(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.START_MULTI_PAY_REQUEST_CODE && resultCode == RESULT_OK) {
            Loading.getInstance().show(getSupportFragmentManager());
            Loading.getInstance().setLoadingText("付费成功，加载中...");
            //step1:删除这个章节以及之后一些章节的缓存
            if (data != null) {
//                mPresenter.removeCacheChangeStatus(data.getIntExtra(Constant.EXTRA_PAY_TYPE, -1));
                //data.getStringExtra(Constant.EXTRA_CHAPTER_ID),
            }
            // step2:重新获取当前章节内容
//            mPageFactory.chapterPaySuccess();
//            mPresenter.reGetCatalogue();
        }
    }

    @Override
    public void onBackPressed() {
        if (isSettingShow()) {
            hideSettingLayout();
            return;
        }
        if (dismissCatalogue()) {
            return;
        }
        if (isShow()) {
            dismiss();
            return;
        }
        super.onBackPressed();
    }


    /**
     * 音量键翻页(原来源码中，声音处理在onKeyUp中，而音量控件的显示与否在哦那onKeyDown中，故还需要重写onKeyDown方法)
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            mReaderManager.toNextPage();
            mReaderView.invalidateBothPage();
            return true;// 返回ture防止翻页有声音
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            mReaderManager.toPrevPage();
            mReaderView.invalidateBothPage();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                return true;//返回turn 不弹出音量控件
            case KeyEvent.KEYCODE_VOLUME_UP:
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private static void startByAnimation(Activity context) {
        context.overridePendingTransition(R.anim.anim_detail_enter, R.anim.anim_no);
    }

    /**
     * 进入动画
     */
    private void enterAnim() {
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator topLayoutAnim = ObjectAnimator.ofFloat(mTitleLayout, "translationY", 0);
        ObjectAnimator bottomLayoutAnim = ObjectAnimator.ofFloat(mBottomLayout, "translationY", 0);
        set.play(topLayoutAnim).with(bottomLayoutAnim);
        set.setDuration(ANIM_DURATION);
        set.addListener(new SimpleAnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                layoutState = STATE_SHOWING;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                layoutState = STATE_SHOW;
            }
        });
        set.start();
    }

    /**
     * 隐藏动画
     */
    private void exitAnim() {
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator topLayoutAnim = ObjectAnimator.ofFloat(mTitleLayout, "translationY", -mTitleLayout.getLayoutParams().height);
        ObjectAnimator bottomLayoutAnim = ObjectAnimator.ofFloat(mBottomLayout, "translationY", mBottomLayout.getLayoutParams().height);
        set.play(topLayoutAnim).with(bottomLayoutAnim);
        set.setDuration(ANIM_DURATION);
        set.addListener(new SimpleAnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                layoutState = STATE_HIDING;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                layoutState = STATE_HIDE;
            }
        });
        set.start();
    }


    @Override
    public void showContent() {
        progressBar.setVisibility(View.GONE);
        mCoordinatorLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void showProgress() {
        mCoordinatorLayout.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void showEmpty() {

    }

}
